﻿using Devonline.Core;
using Hardware.Info;

namespace Devonline.SystemInfo;

/// <summary>
/// 系统信息
/// </summary>
public static class SystemInformation
{
    /// <summary>
    /// 静态方式保存系统信息
    /// </summary>
    private static HardwareInfo? _hardwareInfo { get; set; }
    /// <summary>
    /// 获取系统硬件信息
    /// </summary>
    /// <returns></returns>
    public static HardwareInfo GetSystemInformation()
    {
        if (_hardwareInfo is null)
        {
            _hardwareInfo = new HardwareInfo();
            _hardwareInfo.RefreshAll();
        }

        return _hardwareInfo;
    }

    /// <summary>
    /// 获取 CPU ID
    /// </summary>
    /// <returns></returns>
    public static string GetCPUID()
    {
        var hardwareInfo = new HardwareInfo();
        hardwareInfo.RefreshCPUList();
        return hardwareInfo.CpuList.FirstOrDefault()!.ProcessorId;
    }

    /// <summary>
    /// 获取主要的系统硬件信息, 用于提供设备标识和计算序列号
    /// </summary>
    /// <returns></returns>
    public static ComputerInformation GetComputerInformation()
    {
        var hardwareInfo = GetSystemInformation();
        var bios = hardwareInfo.BiosList.FirstOrDefault()!;
        var computer = hardwareInfo.ComputerSystemList.FirstOrDefault()!;
        var mainboard = hardwareInfo.MotherboardList.FirstOrDefault()!;
        var cpu = hardwareInfo.CpuList.FirstOrDefault()!;
        var gpu = hardwareInfo.VideoControllerList.FirstOrDefault()!;
        var drive = hardwareInfo.DriveList.FirstOrDefault()!;
        var networkAdapter = hardwareInfo.NetworkAdapterList.FirstOrDefault()!;
        return new ComputerInformation
        {
            OperatingSystem = hardwareInfo.OperatingSystem.Name,
            User = Environment.UserName,
            MachineName = Environment.MachineName,
            ComputerName = computer.Version,
            IdentifyingNumber = computer.IdentifyingNumber,
            BIOS = bios.SerialNumber,
            Mainboard = mainboard.SerialNumber,
            CPU = cpu.ProcessorId,
            GPU = gpu.Name,
            HardDrive = drive.SerialNumber,
            NetworkAdapter = networkAdapter.MACAddress,
            DateTime = DateTime.UtcNow
        };
    }

    /// <summary>
    /// 从系统生成序列号
    /// </summary>
    /// <returns></returns>
    public static string GetSerialNumber() => GetComputerInformation().Serialize().GetHashString();
}